#include "constants.h"
#include "types.h"
#include "defs.h"
#include "mm.h"
#include "x86.h"
#include "proc.h"
#include "syscall.h"

int fetchint(uint addr, int *ip) {
	if (addr >= proc->sz || addr + 4 > proc->sz)
		return -1;
	*ip = *(int*) (addr);
	return 0;
}

int fetchstr(uint addr, char **pp) {
	char *s, *ep;

	if (addr >= proc->sz)
		return -1;
	*pp = (char*) addr;
	ep = (char*) proc->sz;
	for (s = *pp; s < ep; s++)
		if (*s == 0)
			return s - *pp;
	return -1;
}

int argint(int n, int *ip) {
	return fetchint(proc->tf->esp + 4 + 4 * n, ip);
}

int argstr(int n, char **pp) {
	int addr;
	if (argint(n, &addr) < 0)
		return -1;
	return fetchstr(addr, pp);
}

extern int sys_fork(void);
extern int sys_getpid(void);
extern int sys_print(void);

static int (*syscalls[])(void) = {
	[SYS_fork] sys_fork,
	[SYS_getpid] sys_getpid,
	[SYS_print] sys_print,
};

void syscall(void) {
	int num;

	num = proc->tf->eax;
	if (num > 0 && num < LENGTH(syscalls) && syscalls[num]) {
		proc->tf->eax = syscalls[num]();
	} else {
		printk("%d %s: unknown sys call %d\n", proc->pid, proc->name, num);
		proc->tf->eax = -1;
	}
}
